<?php
/**
 * 私有API
 * 
 * @author ShuangYa
 * @package EasyAccount
 * @category Controller
 * @link https://www.sylingd.com/
 * @copyright Copyright (c) 2017 ShuangYa
 * @license https://www.sylibs.com/go/easyaccount/license
 */

namespace ea\controller\index;

use \yesf\library\ControllerAbstract;
use ea\model\Config;
use ea\library\Api as ApiLib;

class Api extends ControllerAbstract {
	public static function callAction($request, $response) {
		$dataType = Config::getInstance()->read('privapi_type');
		$key = Config::getInstance()->read('privapi_key');
		if (empty($key)) {
			$result = [
				'error' => '请先在后台将私有API密钥设置为非空'
			];
			goto FINISH_WRITE_RESULT;
		}
		$sign = $request->header['x-priv-sign'];
		if (empty($sign) || $sign !== hash_hmac('md5', $request->rawContent(), $key)) {
			$result = [
				'error' => '签名校验失败'
			];
			goto FINISH_WRITE_RESULT;
		}
		$data = null;
		switch ($dataType) {
			case 'serialize':
				$data = unserialize($request->rawContent());
				break;
			case 'swoole':
				$data = swoole_unserialize($request->rawContent());
				break;
			case 'json':
			default:
				$data = json_decode($request->rawContent(), 1);
				break;
		}
		$rs = ApiLib::dispatch($data['action'], $data);
		if (is_string($rs)) {
			$result = [
				'error' => $rs
			];
		} else {
			$result = &$rs;
		}
FINISH_WRITE_RESULT:
		$result['success'] = !isset($result['error']);
		switch ($dataType) {
			case 'serialize':
				$response->header('Content-Type', 'text/plain');
				$response->write(serialize($result));
				break;
			case 'swoole':
				$response->header('Content-Type', 'application/octet-stream');
				$response->write(swoole_serialize($result));
				break;
			case 'json':
			default:
				$response->header('Content-Type', 'application/json; charset=UTF-8');
				$response->write(json_encode($result));
				break;
		}
	}
}